<!-- src/pagesMember/pages/profile/profile.vue -->
<script setup lang="ts">
// 获取屏幕边界到安全区域距离
import { getMemberProfileApi, updateMemberProfileApi } from '@/pagesMember/api/profile.ts'
import type { ProfileDetail } from '@/types/profile'
import { ref } from 'vue'
import { useMemberStore } from '@/stores'
import debounce from 'lodash.debounce'

const { safeAreaInsets } = uni.getWindowInfo()

// form 是后端给的数据，其中一部分数据用于表单渲染
// form 里有一部分数据不是后端要求传递的，但是后端对于那些多余的数据是不会处理的，别管他
const form = ref<ProfileDetail>({} as ProfileDetail)
const getMemberProfile = async () => {
  // 获取用户信息
  const res = await getMemberProfileApi()
  form.value = res.result
}
getMemberProfile()

// 获取Store
const memberStore = useMemberStore()

// 上传头像
const uploadAvatar = (filePath: string) => {
  uni.uploadFile({
    url: '/member/profile/avatar',
    filePath,
    name: 'file',
    success(uploadRes) {
      if (uploadRes.statusCode === 200) {
        // 提取头像
        const { avatar } = JSON.parse(uploadRes.data).result
        // 当前页面更新头像
        form.value.avatar = avatar
        // 更新 Store 头像
        memberStore.updateAvatar(avatar)
        uni.showToast({ icon: 'success', title: '头像更新成功' })
      } else {
        uni.showToast({ icon: 'error', title: '头像更新失败' })
      }
    },
  })
}

// 修改头像
const onAvatarChange = () => {
  // #ifdef APP-PLUS || H5
  // 调用 uni.chooseImage 方法，选择图片，只有 app 端和网页端才支持
  uni.chooseImage({
    count: 1, // 最多可以选择的图片张数，默认9
    mediaType: ['image'],
    success(chooseImageRes) {
      const tempFilePath = chooseImageRes.tempFilePaths[0]
      uploadAvatar(tempFilePath)
    },
  })
  // #endif
  // #ifdef MP-WEIXIN
  // 只有小程序端可以使用
  uni.chooseMedia({
    count: 1, // 最多可以选择的图片张数，默认9
    mediaType: ['image'],
    success(chooseImageRes) {
      const { tempFilePath } = chooseImageRes.tempFiles[0]
      uploadAvatar(tempFilePath)
    },
  })
  // #endif
}

// 修改性别
const changeGender: UniHelper.RadioGroupOnChange = (e) => {
  form.value.gender = e.detail.value as ProfileDetail['gender']
}

// 修改生日
const changeBirthday: UniHelper.DatePickerOnChange = (e) => {
  form.value.birthday = e.detail.value
}

// 修改城市
let fullLocationCode: [string, string, string] = ['', '', '']
// #ifdef MP-WEIXIN
const changeFullLocationWx: UniHelper.RegionPickerOnChange = (e) => {
  form.value.fullLocation = e.detail.value.join(' ')
  fullLocationCode = e.detail.code!
}
// #endif

// #ifdef APP-PLUS || H5
const changeFullLocationAppH5: UniHelper.UniDataPickerOnChange = (e) => {
  const fullLocations = e.detail.value
  form.value.fullLocation = fullLocations.map((item) => item.text).join(' ')
  fullLocationCode = fullLocations.map((item) => item.value) as [string, string, string]
}
// #endif

// 提交表单
const onSubmit = debounce(async () => {
  const res = await updateMemberProfileApi({
    // form 里有一部分数据不是后端要求传递的，但是后端对于那些多余的数据是不会处理的，别管他
    ...form.value,
    // 第一次拿到后端数据的时候，是没有 Code 的，只有省市区的字符串，此时 Code 都是空字符串
    // 只有调用了 changeFullLocationWx 后，才会有 Code，所以如果没有 Code，就得传递 undefined
    // uni.request 很智能，不会携带值为 undefined 的参数作为参数
    provinceCode: fullLocationCode[0] || undefined,
    cityCode: fullLocationCode[1] || undefined,
    countyCode: fullLocationCode[2] || undefined,
  })
  // 更新昵称
  if (res.result.nickname) memberStore.updateNickname(res.result.nickname)

  // 成功提示
  uni.showToast({ icon: 'success', title: '保存成功' })
  // 返回上一页
  setTimeout(() => {
    uni.navigateBack()
  }, 1000)
}, 500)
</script>

<template>
  <view class="viewport">
    <!-- 导航栏 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <navigator open-type="navigateBack" class="back icon-left" hover-class="none"></navigator>
      <view class="title">个人信息</view>
    </view>
    <!-- 头像 -->
    <view class="avatar">
      <view class="avatar-content" @tap="onAvatarChange">
        <image class="image" :src="form.avatar" mode="aspectFill" />
        <text class="text">点击修改头像</text>
      </view>
    </view>
    <!-- 表单 -->
    <form>
      <!-- 表单内容 -->
      <view class="form-content">
        <view class="form-item">
          <text class="label">账号</text>
          <text class="account">{{ form.account }}</text>
        </view>
        <view class="form-item">
          <text class="label">昵称</text>
          <input class="input" type="text" placeholder="请填写昵称" v-model="form.nickname" />
        </view>
        <view class="form-item">
          <text class="label">性别</text>
          <radio-group @change="changeGender">
            <label>
              <radio value="男" color="#27ba9b" :checked="form.gender === '男'" />
              男
            </label>
            <label>
              <radio value="女" color="#27ba9b" :checked="form.gender === '女'" />
              女
            </label>
          </radio-group>
        </view>
        <view class="form-item">
          <text class="label">生日</text>
          <picker
            class="picker"
            mode="date"
            start="1900-01-01"
            :end="new Date()"
            :value="form.birthday"
            @change="changeBirthday"
          >
            <view v-if="form.birthday">{{ form.birthday }}</view>
            <view class="placeholder" v-else>请选择日期</view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">城市</text>
          <!-- #ifdef MP-WEIXIN -->
          <picker
            class="picker"
            mode="region"
            :value="form.fullLocation?.split(' ')"
            @change="changeFullLocationWx"
          >
            <view v-if="form.fullLocation">{{ form.fullLocation }}</view>
            <view class="placeholder" v-else>请选择城市</view>
          </picker>
          <!-- #endif -->
          <!-- #ifdef APP-PLUS || H5 -->
          <uni-data-picker
            class="picker"
            popup-title="请选择城市"
            collection="opendb-city-china"
            field="code as value, name as text"
            orderby="value asc"
            :step-searh="true"
            self-field="code"
            parent-field="parent_code"
            @change="changeFullLocationAppH5"
          >
            <view v-if="form.fullLocation">{{ form.fullLocation }}</view>
            <view class="placeholder" v-else>请选择城市</view>
          </uni-data-picker>
          <!-- #endif -->
        </view>
        <view class="form-item">
          <text class="label">职业</text>
          <input class="input" type="text" placeholder="请填写职业" v-model="form.profession" />
        </view>
      </view>
      <!-- 提交按钮 -->
      <button class="form-button" @tap="onSubmit">保 存</button>
    </form>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: auto 420rpx;
  background-repeat: no-repeat;
}

/* 导航栏 */
.navbar {
  position: relative;

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }

  .back {
    position: absolute;
    height: 40px;
    width: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

/* 头像 */
.avatar {
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    background-color: #eee;
  }

  .text {
    display: block;
    padding-top: 20rpx;
    line-height: 1;
    font-size: 26rpx;
    color: #fff;
  }
}

/* 表单 */
form {
  background-color: #f4f4f4;

  .form-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  .form-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    /* #ifdef APP-PLUS || H5 */

    // 处理 uni-data-picker 样式的一个 bug
    :deep(.selected-area) {
      height: auto;
      flex: 0 1 auto;
    }

    /* #endif */

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    label {
      margin-right: 20rpx;

      radio {
        transform: scale(70%);
      }
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }

  .form-button {
    height: 80rpx;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #27ba9b;
  }
}
</style>
